package com.wujunshen.algorithm.leetcode.basic;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2022/7/24 18:27<br>
 */
public class 旋转链表 {
  public ListNode rotateRight(ListNode head, int k) {
    if (head == null || k == 0) {
      return head;
    }

    // 算长度和最后一个ListNode
    int length = 0;
    ListNode temp = head;
    ListNode tail = null;
    while (temp != null) {
      tail = temp;
      temp = temp.next;
      length++;
    }

    k = k % length;

    ListNode p = head;
    for (int i = 0; i < length - k - 1; i++) {
      p = p.next;
    }

    tail.next = head;
    head = p.next;
    p.next = null;

    return head;
  }
}
